<template>
  <a-card class="content" :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="类目ID">
              <a-input v-model="queryParam.id" placeholder ref="searchid" />
            </a-form-item>
          </a-col>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span
              class="table-page-search-submitButtons"
              :style="advanced && { float: 'right', overflow: 'hidden' } || {} "
            >
              <a-button type="primary" @click="search()">查询</a-button>
              <a-button style="margin-left: 8px" @click="clear()">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="addForm()">新建</a-button>
    </div>

    <a-table
      ref="table"
      size="default"
      rowKey="value"
      :columns="goodsCategoryColumns"
      :pagination="pagination"
      @change="handleTableChange"
      :dataSource="loadData"
      class="catelist"
    >
      <span slot="level" slot-scope="text">
        <a-tag color="blue" v-if="text === 0">一级类目</a-tag>
        <a-tag color="blue" v-if="text === 1">二级类目</a-tag>
        <a-tag color="blue" v-if="text === 2">三级类目</a-tag>
        <a-tag color="blue" v-if="text === 3">四级类目</a-tag>
      </span>
      <span slot="picUrl" slot-scope="text">
        <img :src="text" width="40" />
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a-button type="primary"  class="flyray-btn"
        @click="editForm(record)"
       >修改</a-button>

          <a-button
            type="danger"
            class="table-danger flyray-btn"
            @click="() => del(record)"
          >删除</a-button>
        </template>
      </span>
    </a-table>
    <div>
      <a-modal :title="title" v-model="visible" @ok="handleSubmit" width="700px">
        <a-form :form="form">
          <a-form-item
            label="类目名称"
            :colon="false"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 12 }"
          >
            <a-input
              v-decorator="['title', { rules: [{ required: true, message: '类目名不能为空！' }] }]"
            />
          </a-form-item>
          <a-form-item label="类目图片" :colon="false" :label-col="{ span: 5 }" class="cateimg">
            <a-upload
              listType="picture-card"
              class="avatar-uploader"
              :showUploadList="false"
              action="http://admin.huajianmo.com/api/upload/admin"
              :beforeUpload="beforeUpload"
              @change="handleChange"
            >
              <img v-if="imageUrl" style="width: 100px;height:100px" :src="imageUrl" alt="avatar" />
              <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
              </div>
            </a-upload>
          </a-form-item>
          <a-form-item
            label="父类目"
            :colon="false"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 15 }"
          >
            <el-cascader
              ref="cascader"
              @change="handleChange2()"
              :options="options1"
              :props="{ checkStrictly: true }"
              clearable
              v-model="parentId"
            ></el-cascader>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </a-card>
</template>

<script>
import goodsDetail from './goodsDetail'
import { queryGoodsCategory,categorySecondLevelTree, addCategory, categoryEdit,deleteCategory } from '@/api/mall/goodsCategory'
import { goodsCategoryColumns } from '@/const/crud/mall/goodsCategory.config'
import { note } from 'ant-design-vue/es/_util/warning'

const statusMap = {
  0: {
    status: 'default',
    text: '关闭'
  },
  1: {
    status: 'processing',
    text: '运行中'
  },
  2: {
    status: 'success',
    text: '已上线'
  },
  3: {
    status: 'error',
    text: '异常'
  }
}
function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
export default {
  components: {
    goodsDetail
  },
  data() {
    return {
      parameter: {
        pageSize: 10,
        orderNo: null,
        pageNo: 1,
        status: undefined
      },
      pagination: {//分页
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showTotal: total => `共有${total}条`
      },
      title: '',
      action: '0',
      id: '',
      parentId: 0,
      options1: [],
      // 图片上传
      loading: false,
      imageUrl: '',
      // 表单
      form: this.$form.createForm(this),
      // 模态框
      visible: false,
      visible2: false,
      goodsCategoryColumns,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      loadData: [],
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        alert: {
          show: true,
          clear: () => {
            this.selectedRowKeys = []
          }
        },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: false
    }
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    },
    statusTypeFilter(type) {
      return statusMap[type].status
    },
  },
  created() {
    this.tableOption()
    this.getData()
    this.categorySecondLevelTree()
  },
  methods: {
    categorySecondLevelTree(){
        categorySecondLevelTree(Object.assign(this.parameter)).then(res => {
          console.log("获取树")
          this.options1 = res.data
        })
    },
    getData() {
      queryGoodsCategory(Object.assign(this.parameter)).then(res => {
        //把数据赋值给loadData
        this.loadData = res.data
        //总条数
        this.loading = false
      })
    },
    handleTableChange(pagination) {//分页
      this.parameter.pageNo = pagination.current
      this.parameter.pageSize = pagination.pageSize
      this.getData()
    },
    clear() {
      this.queryParam.id = ''
      this.getData()
    },
    search() {
      this.getData()
    },
    addForm(val) {
      this.visible = true
      this.title = "新建"
      this.action = '0'
      this.form.resetFields()
      this.imageUrl = ''
      this.parentId = ''
    },
    editForm(val) {
      this.visible = true
      this.title = "编辑"
      this.action = '1'
      console.log(val)
      this.id = val.id
      setTimeout(() => {
        //延时处理，避免出现渲染之前回显数据报错
        this.form.setFieldsValue({
          //设置回显参数
           //设置回显参数
          title: val.label,
        })
      }, 0)
      this.imageUrl = val.picUrl
      this.parentId = val.parentId
    },
    handleChange(info) {
      console.log("图片上传")
      console.log(info)
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        this.addForm.picUrl = info.file.response.url
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
          this.loading = false
        })
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJpgOrPng && isLt2M
    },
    handleChange2(value) {
      let nodesObj = this.$refs['cascader'].getCheckedNodes()
      console.log(nodesObj[0].data.value)
      this.parentId = nodesObj[0].data.value
    },
    // 模态框
    showModal() {
      this.visible = true
    },
    handleSubmit(e) {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.visible = false
          console.log(values)
          this.addForm.title = values.title
          this.addForm.parentId = this.parentId
          if(this.action == 1){
            this.addForm.id = this.id
            categoryEdit(this.addForm).then(res => {
              this.getData()
            })
          }else{
            addCategory(this.addForm).then(res => {
              this.getData()
            })
          }
        }
      })
    },
    tableOption() {
      if (!this.optionAlertShow) {
        this.options = {
          alert: {
            show: true,
            clear: () => {
              this.selectedRowKeys = []
            }
          },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange,
            getCheckboxProps: record => ({
              props: {
                disabled: record.no === 'No 2',
                name: record.no
              }
            })
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },

    del(row) {
      var that = this
      this.$confirm({
        title: '警告',
        content: `真的要删除 ${row.id} 吗?`,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          // 在这里调用删除接口
          that.addForm.id = row.id
          deleteCategory(that.addForm).then(res => {
            that.getData()
          })

        }
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
<style scope>

.flyray-btn {
  font-size: 12px;
  padding: 0 7px;
  margin: 0 0 0 3px;
  height: 24px;

}
.cateimg .ant-upload-picture-card-wrapper {
  width: 112px;
  height: 112px;
}
.cateimg .ant-upload-picture-card-wrapper .ant-upload.ant-upload-select-picture-card {
  width: 112px;
  height: 112px;
  overflow: hidden;
}
.cateimg .ant-upload-picture-card-wrapper img {
  width: 112px;
  height: 112px;
  overflow: hidden;
}
.catelist tr button {
  margin: 0 5px 5px 5px;
  border: 0;
}

.table-danger{
    color: #fff;
    background-color: #ff4d4f ;
    border-color: #ff4d4f ;
    margin-left: 5px;

}

</style>